<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <PageHeader 
      title="供应商管理" 
      description="管理您的供应商信息，进行批量导入/导出、数据清洗等数据维护操作"
      icon="OfficeBuilding"
    />
    
    <!-- 添加提示信息 -->
    <div class="data-management-tip" v-if="showDataManagementTip">
      <el-alert
        title="提示：此页面用于批量数据维护。如需进行日常业务操作，请前往【采购管理 → 供应商管理】"
        type="info"
        show-icon
        closable
        @close="handleTipClose"
      >
        <template #default>
          <div class="tip-content">
            <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
            <el-link type="primary" @click="goToProcurementManagement">采购管理 → 供应商管理</el-link>
          </div>
        </template>
      </el-alert>
    </div>
    
    <!-- 智能洞察 -->
    <SmartInsights 
      v-if="stats && Object.keys(stats).length > 0"
      :insights="smartInsights"
      @action="handleInsightAction"
    />
    
    <!-- 供应商统计 -->
    <SupplierStats 
      :stats="stats"
      :loading="loading"
    />
    
    <!-- 功能区域 -->
    <el-card class="function-area" shadow="never">
      <el-row :gutter="20">
        <el-col :span="16">
          <SupplierFilter 
            :query-params="queryParams"
            @search="handleSearch"
            @reset="handleReset"
          />
        </el-col>
        <el-col :span="8">
          <div class="function-buttons">
            <el-dropdown trigger="click" @command="handleBatchCommand">
              <el-button class="batch-btn">
                批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">导出供应商</el-dropdown-item>
                  <el-dropdown-item command="import">导入供应商</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除供应商</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 供应商表格 -->
    <SupplierTable
      :suppliers="suppliers"
      :loading="loading"
      :pagination="pagination"
      :selected-suppliers="selectedSuppliers"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @command="handleTableCommand"
    />
    
    <!-- 新增供应商抽屉 -->
    <SupplierOperationDialog
      v-model="addDrawerVisible"
      :editing-supplier="null"
      @submit="createSupplier"
      @close="handleAddDrawerClose"
    />
    
    <!-- 编辑供应商抽屉 -->
    <SupplierOperationDialog
      v-model="editDrawerVisible"
      :editing-supplier="editingSupplier"
      @submit="updateSupplier"
      @close="handleEditDrawerClose"
    />
    
    <!-- 供应商详情抽屉 -->
    <SupplierDetail
      v-model="detailDrawerVisible"
      :supplier="detailSupplier"
      @edit="handleEditSupplier"
      @close="handleDetailDrawerClose"
    />
    
    <!-- 供应商导入向导 -->
    <SupplierImportWizard
      v-model="importWizardVisible"
      @import-success="handleImportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  OfficeBuilding, Plus, ArrowDown, Upload, Download, Delete 
} from '@element-plus/icons-vue'
import * as supplierAPI from '@/api/procurement'
import { getSupplierStats } from '@/api/procurement'
import type { Supplier } from '@/types/supplier'

// 使用路由
const router = useRouter()

// 导入组件
import PageHeader from '@/components/layout/PageHeader.vue'
import SmartInsights from '@/components/insights/SmartInsights.vue'
import SupplierStats from '@/views/purchase/components/SupplierStats.vue'
import SupplierFilter from '@/views/purchase/components/SupplierFilter.vue'
import SupplierTable from '@/views/purchase/components/SupplierTable.vue'
import SupplierOperationDialog from '@/views/purchase/components/SupplierOperationDialog.vue'
import SupplierDetail from '@/views/purchase/components/SupplierDetail.vue'
import SupplierImportWizard from '@/views/purchase/components/SupplierImportWizard.vue'

interface SupplierQueryParams {
  name: string
  status: string
  level: string
  type: string
  region: string[]
  industry: string
  supplierSource: string
  responsiblePurchaser: string
  minAnnualAmount?: number
  maxAnnualAmount?: number
  page: number
  limit: number
}

interface SupplierStats {
  totalSuppliers: number
  activeSuppliers: number
  keySuppliers: number
  newSuppliers: number
  supplierTrend: number
  newSupplierTrend: number
  activeSupplierTrend: number
  keySupplierTrend: number
}

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 跳转到采购管理
const goToProcurementManagement = () => {
  router.push('/procurement/suppliers')
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 响应式数据
const suppliers = ref<Supplier[]>([])
const loading = ref(false)
const addDrawerVisible = ref(false)
const editDrawerVisible = ref(false)
const detailDrawerVisible = ref(false)
const importWizardVisible = ref(false)
const detailSupplier = ref<Supplier | null>(null)
const editingSupplier = ref<Supplier | null>(null)
const selectedSuppliers = ref<Supplier[]>([])
const stats = ref<SupplierStats>({
  totalSuppliers: 0,
  activeSuppliers: 0,
  keySuppliers: 0,
  newSuppliers: 0,
  supplierTrend: 0,
  newSupplierTrend: 0,
  activeSupplierTrend: 0,
  keySupplierTrend: 0
})

const smartInsights = ref([
  {
    id: '1',
    type: 'opportunity',
    title: '高价值供应商增长',
    description: '本月新增5个VIP供应商，同比增长25%',
    priority: 'high',
    suppliers: [],
    confidence: 85,
    action: () => ElMessage.info('查看高价值供应商详情')
  },
  {
    id: '2',
    type: 'risk',
    title: '供应商风险预警',
    description: '3个重要供应商近30天无交易，建议及时跟进',
    priority: 'high',
    suppliers: [],
    confidence: 78,
    action: () => ElMessage.info('查看风险预警供应商')
  }
])

const queryParams = reactive<SupplierQueryParams>({
  name: '',
  status: '',
  level: '',
  type: '',
  region: [],
  industry: '',
  supplierSource: '',
  responsiblePurchaser: '',
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 计算属性
const activeSuppliers = computed(() => {
  return suppliers.value.filter(supplier => supplier.status === 1)
})

// 生命周期钩子
onMounted(() => {
  loadSuppliers()
  loadStats()
})

// 方法
const loadSuppliers = async () => {
  loading.value = true
  try {
    const response = await supplierAPI.getSuppliers({
      ...queryParams,
      page: pagination.page,
      limit: pagination.limit
    })
    
    if (response.success) {
      suppliers.value = response.data.list.map((supplier: any) => ({
        ...supplier,
        // 确保contactPersons是数组格式
        contactPersons: supplier.contactPersons && Array.isArray(supplier.contactPersons) 
          ? supplier.contactPersons 
          : (supplier.contactPersons ? JSON.parse(supplier.contactPersons) : [])
      }))
      pagination.total = response.data.pagination.total
    } else {
      ElMessage.error(response.message || '获取供应商列表失败')
    }
  } catch (error) {
    ElMessage.error('获取供应商列表失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getSupplierStats()
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取供应商统计失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadSuppliers()
}

const handleReset = () => {
  Object.assign(queryParams, {
    name: '',
    status: '',
    level: '',
    type: '',
    region: [],
    industry: '',
    supplierSource: '',
    responsiblePurchaser: '',
    minAnnualAmount: undefined,
    maxAnnualAmount: undefined
  })
  pagination.page = 1
  loadSuppliers()
}

const handleSelectionChange = (selection: Supplier[]) => {
  selectedSuppliers.value = selection
}

const handleRowClick = (row: Supplier) => {
  showDetailDrawer(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  // 处理排序逻辑
  loadSuppliers()
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadSuppliers()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadSuppliers()
}

const handleTableCommand = (command: { action: string, row: Supplier }) => {
  const { action, row } = command
  switch (action) {
    case 'detail':
      showDetailDrawer(row)
      break
    case 'edit':
      showEditDrawer(row)
      break
    case 'orders':
      viewSupplierOrders(row)
      break
    case 'delete':
      deleteSupplier(row)
      break
  }
}

const showAddDrawer = () => {
  addDrawerVisible.value = true
}

const showEditDrawer = (supplier: Supplier) => {
  editingSupplier.value = supplier
  editDrawerVisible.value = true
}

const showDetailDrawer = (supplier: Supplier) => {
  detailSupplier.value = supplier
  detailDrawerVisible.value = true
}

const handleEditSupplier = (supplier: Supplier) => {
  detailDrawerVisible.value = false
  showEditDrawer(supplier)
}

const viewSupplierOrders = (supplier: Supplier) => {
  // 跳转到供应商订单页面
  ElMessage.info(`查看供应商 ${supplier.name} 的订单`)
}

const deleteSupplier = async (supplier: Supplier) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除供应商 "${supplier.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    const response = await supplierAPI.deleteSupplier(supplier.id)
    if (response.success) {
      ElMessage.success('供应商删除成功')
      loadSuppliers()
    } else {
      ElMessage.error(response.message || '删除供应商失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除供应商失败')
    }
  }
}

const createSupplier = async (supplierData: Supplier) => {
  try {
    const response = await supplierAPI.createSupplier(supplierData)
    if (response.success) {
      ElMessage.success('供应商创建成功')
      addDrawerVisible.value = false
      loadSuppliers()
      loadStats()
    } else {
      ElMessage.error(response.message || '创建供应商失败')
    }
  } catch (error) {
    ElMessage.error('创建供应商失败')
  }
}

const updateSupplier = async (supplierData: Supplier) => {
  try {
    const response = await supplierAPI.updateSupplier(supplierData.id, supplierData)
    if (response.success) {
      ElMessage.success('供应商更新成功')
      editDrawerVisible.value = false
      loadSuppliers()
    } else {
      ElMessage.error(response.message || '更新供应商失败')
    }
  } catch (error) {
    ElMessage.error('更新供应商失败')
  }
}

const handleBatchCommand = (command: string) => {
  switch (command) {
    case 'export':
      exportSuppliers()
      break
    case 'import':
      importWizardVisible.value = true
      break
    case 'delete':
      batchDeleteSuppliers()
      break
  }
}

const exportSuppliers = () => {
  ElMessage.info('导出供应商功能开发中')
}

const batchDeleteSuppliers = async () => {
  if (selectedSuppliers.value.length === 0) {
    ElMessage.warning('请先选择要删除的供应商')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedSuppliers.value.length} 个供应商吗？此操作不可恢复。`,
      '批量删除确认',
      {
        type: 'warning'
      }
    )
    
    const ids = selectedSuppliers.value.map(supplier => supplier.id)
    const response = await supplierAPI.batchDeleteSuppliers(ids)
    if (response.success) {
      ElMessage.success('批量删除供应商成功')
      loadSuppliers()
      loadStats()
    } else {
      ElMessage.error(response.message || '批量删除供应商失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除供应商失败')
    }
  }
}

const handleAddDrawerClose = () => {
  addDrawerVisible.value = false
}

const handleEditDrawerClose = () => {
  editDrawerVisible.value = false
  editingSupplier.value = null
}

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false
  detailSupplier.value = null
}

const handleImportSuccess = () => {
  importWizardVisible.value = false
  loadSuppliers()
  loadStats()
}

const handleInsightAction = (insight: any) => {
  insight.action()
}
</script>

<style scoped>
.supplier-management {
  padding: 20px;
}

.function-area {
  margin: 20px 0;
  border-radius: 8px;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  align-items: center;
  height: 100%;
}

.add-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.add-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.batch-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.batch-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .supplier-management {
    padding: 10px;
  }
  
  .function-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .add-btn,
  .batch-btn {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>